import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { request } from '@/utils/request'
import type { Workflow, WorkflowResponse } from '@/types/workflow'
import { RequestError } from '@/utils/request'

// 工作流数据
const workflowData = ref<Partial<Workflow>>({
  name: '',
  description: '',
  workflow_json: {},
  category: 'default'
});

const saving = ref(false);
const route = useRoute();
const router = useRouter();

// 保存并跳转到下一步
const saveAndNext = async () => {
  try {
    saving.value = true;

    // 验证必要字段
    if (!workflowData.value.name?.trim()) {
      throw new Error('请输入工作流名称');
    }

    if (!workflowData.value.workflow_json || Object.keys(workflowData.value.workflow_json).length === 0) {
      throw new Error('工作流配置不能为空');
    }

    // 准备请求数据
    const requestData = {
      name: workflowData.value.name.trim(),
      description: workflowData.value.description?.trim() || '',
      workflow_json: workflowData.value.workflow_json,
      category: workflowData.value.category || 'default'
    };

    // 输出 workflow_json 的类型和值，便于调试格式
    console.log('workflow_json 类型和值:', typeof workflowData.value.workflow_json, workflowData.value.workflow_json);

    // 如果 workflow_json 为字符串，则解析为对象
    if (typeof requestData.workflow_json === 'string') {
      try {
        requestData.workflow_json = JSON.parse(requestData.workflow_json);
      } catch (error) {
        throw new Error('工作流配置格式无效，无法解析为对象');
      }
    }

    const result = await request<WorkflowResponse>(
      `/api/v1/workflows/${route.params.id}`,
      {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: requestData
      }
    );

    ElMessage.success('保存成功');
    return result;
  } catch (error) {
    let errorMessage = '保存失败';
    let errorDetails = '';

    if (error instanceof RequestError) {
      errorDetails = typeof error.details === 'string' 
        ? error.details 
        : JSON.stringify(error.details);
      
      console.error('保存工作流失败:', {
        status: error.status,
        details: error.details,
        requestData: {
          id: route.params.id,
          name: workflowData.value.name,
          category: workflowData.value.category,
          workflow_json_type: typeof workflowData.value.workflow_json
        }
      });
    } else {
      errorDetails = error instanceof Error ? error.message : '未知错误';
    }

    ElMessage.error({
      message: `${errorMessage}: ${errorDetails}`,
      duration: 5000,
      showClose: true
    });
    throw error;
  } finally {
    saving.value = false;
  }
};

// 加载工作流数据
const loadWorkflow = async (id: string) => {
  try {
    const response = await request<WorkflowResponse>(`/api/v1/workflows/${id}`);
    if (!response?.data) {
      throw new Error('加载工作流失败');
    }

    // 确保 workflow_json 字段存在且为对象
    if (!response.data.workflow_json) {
      response.data.workflow_json = {};
      console.warn('工作流配置为空，已初始化为空对象');
    } else if (typeof response.data.workflow_json === 'string') {
      try {
        response.data.workflow_json = JSON.parse(response.data.workflow_json);
        console.log('已解析工作流配置:', response.data.workflow_json);
      } catch (error) {
        console.error('解析 workflow_json 失败:', error);
        response.data.workflow_json = {};
      }
    }

    // 确保 param_schema 字段存在
    if (!response.data.param_schema) {
      response.data.param_schema = {};
    }

    workflowData.value = response.data;
    
    // 添加更详细的日志
    console.log('加载的工作流数据:', {
      id: response.data.id,
      name: response.data.name,
      category: response.data.category,
      workflow_json: response.data.workflow_json,
      param_schema: response.data.param_schema
    });

  } catch (error) {
    console.error('加载工作流失败:', error);
    ElMessage.error({
      message: '加载工作流失败: ' + (error instanceof Error ? error.message : '未知错误'),
      duration: 5000,
      showClose: true
    });
    // 初始化默认值
    workflowData.value = {
      name: '',
      description: '',
      workflow_json: {},
      param_schema: {},
      category: 'default'
    };
  }
};

// 在组件挂载时加载数据
onMounted(() => {
  if (route.params.id) {
    console.log('开始加载工作流:', route.params.id);
    loadWorkflow(route.params.id as string);
  }
}); 